package com.example.javamaday.leetcode;

import com.example.javamaday.leetcode.base.ListNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class LeetCodeTest0025 {

    public static void main(String[] args) {
        // [1,2,3,4,5]   2
        ListNode listNode = new ListNode(1);
        listNode.next = new ListNode(2);
        listNode.next.next = new ListNode(3);
        listNode.next.next.next = new ListNode(4);
        listNode.next.next.next.next = new ListNode(5);
        new LeetCodeTest0025().reverseKGroup(listNode, 2);
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || k == 1) {
            return head;
        }
        List<ListNode> nodeList = new ArrayList<>();
        ListNode current = head;
        while (current != null) {
            ListNode helper = current.next;
            current.next = null;
            nodeList.add(current);
            current = helper;
        }
        int partIndex = 1;
        List<ListNode> resultList = new LinkedList<>();
        while (partIndex * k <= nodeList.size()) {
            for (int i = partIndex * k; i > (partIndex - 1) * k; i--) {
                resultList.add(nodeList.get(i - 1));
            }
            partIndex++;
        }
        // 补足数据
        if (resultList.size() < nodeList.size()) {
            for (int i = resultList.size(); i < nodeList.size(); i++) {
                resultList.add(nodeList.get(i));
            }
        }
        ListNode newHead = resultList.get(0);
        current = newHead;
        for (int i = 1; i < resultList.size(); i++) {
            current.next = resultList.get(i);
            current = current.next;
        }
        return newHead;
    }


}
